<?php

class Image
{
	 private $uploaddir_full;
	 private $uploaddir_mini;
     public static $error_msg;     
	 
	  public function __construct()
	 {
		 $this->uploaddir_full="user_photos/full_size/";
		 $this->uploaddir_mini="user_photos/mini/";		 
	 }
	 
	 public function move ($file_array, $file_to='full')
	 {		
		 switch ($file_to)
		 {
			 case "full":
				 $file_to= $this->uploaddir_full. $this->random_file_name (). '.'.$this->get_file_ext(basename($file_array['file']['name']));
				 break;
			 case "mini":
				 $file_to= $this->uploaddir_mini . $this->random_file_name (). '.'.$this->get_file_ext(basename($file_array['file']['name']));
				 break;
		 }

		if (move_uploaded_file($file_array['file']['tmp_name'], $file_to))
		{   
			list($current_width, $current_height) = getimagesize($file_to);	
			
			if ($current_width > 770)
			{
				 $new_name=$this->uploaddir_full. $this->random_file_name (). '.'.$this->get_file_ext(basename($file_array['file']['name']));
				 
				 if ($this->resize_image($file_to, $new_name))
				 {
					 unlink($file_to);
					 return $new_name."width:".$current_width;
				 }
			}
			return $file_to."width:".$current_width;			
		} 
		else
		{
			return false;
		}
	 }
     
     public function moveAll ($file_array, $photoalbums_id, $user_id)
     {
         self::$error_msg = "";
         $photolist=array();   
         
         foreach ($file_array['photos']['name'] as $name => $value)
         {
             $new_name_simple=$this->random_file_name (). '.'.$this->get_file_ext(basename($file_array['photos']['name'][$name]));
			 $photolist[]=$new_name_simple;
			 $new_name=$this->uploaddir_full.$new_name_simple;
                          
             if (!move_uploaded_file($file_array['photos']['tmp_name'][$name], $new_name))
             {
                 self::$error_msg = self::$error_msg." Cant move ".$file_array['photos']['tmp_name'][$name]." to $new_name"; 
                 return false;
             }
			 else
			 {
				 $this->resize_image($new_name, $this->uploaddir_mini.$new_name_simple, "auto", 180);
                 $replace_data=array
                 (
                     'user_id'=>$user_id,
                     'title'=>'Без названия', 
                     'pu_photoalbums_id'=>$photoalbums_id,
                     'link'=>$new_name_simple, 
                     'date'=>time()
                 );
                 SQL::execute(Template::render("insertPhotoToAlbum.sql", "sql", $replace_data));   
			 }
         }         
         return $photolist;
     }
	 
	 private function random_file_name ()
	 {
		 $first_part=mt_rand(1000, 9999);
		 $second_part=mt_rand(1000, 9999);
		 $third_part=mt_rand(1000, 9999);
		 
		 return $first_part."_".$second_part."_".$third_part;
	 }
	 
	 private function get_file_ext($filename) 
	 {
		 return substr(strrchr($filename, '.'), 1);
	 }
	 
	 		
	private function resize_image($src, $dest, $width=770, $height="auto", $rgb=0xFFFFFF, $quality=100)
	{
		if (!file_exists($src)) 
		{
			 return false;
		}

		 $size = getimagesize($src);

		if ($size === false) 
		{
			 return false;
		}

		$format = strtolower(substr($size['mime'], strpos($size['mime'], '/')+1));
		$icfunc = "imagecreatefrom" . $format;
		if (!function_exists($icfunc))
		{
			 return false;
		}

				
		if ($height=="auto")
		{
			 $x_ratio = $width/$size[0] ;
			 $y_ratio =  $x_ratio;
			 $height=$size[1]/($size[0]/$width);
		}
		else
		{
			 $y_ratio =  $height/$size[1] ;
		}
		
		if ($width=="auto")
		{
			 $y_ratio =  $height/$size[1] ;
			 $x_ratio =  $y_ratio;
			 $width=$size[0]/($size[1]/$height);
		}
		else
		{
			 $x_ratio = $width/$size[0] ;
		}	
		

		$ratio      = min($x_ratio, $y_ratio);
		$use_x_ratio = ($x_ratio == $ratio);

		$new_width   = $use_x_ratio  ? $width  : floor($size[0] * $ratio);
		$new_height  = !$use_x_ratio ? $height : floor($size[1] * $ratio);

		$new_left    = $use_x_ratio  ? 0 : floor(($width - $new_width) / 2);
		$new_top     = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);

		$isrc = $icfunc($src);
		$idest = imagecreatetruecolor($width, $height);

		imagefill($idest, 0, 0, $rgb);
		imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]);

		imagejpeg($idest, $dest, $quality);

		imagedestroy($isrc);
		imagedestroy($idest);

		return true;
	}
	
	 public function createAvatar($crop_data, $crop_width=182, $crop_height = 258, $size="full")
	 {
		 $filename = $crop_data['file'];
		 
		 if ($size=="full")
		 {
			 $new_filename = $this->uploaddir_full. $this->random_file_name () . '.'.$this->get_file_ext(basename($filename));
		 }
		 else
		 {
			 $new_filename = $this->uploaddir_mini. $this->random_file_name () . '.'.$this->get_file_ext(basename($filename));
		 }
		 		 
		 $size = getimagesize($filename);
		 $format = strtolower(substr($size['mime'], strpos($size['mime'], '/')+1));
		 $icfunc = "imagecreatefrom" . $format;
		 if (!function_exists($icfunc))
		 {
			 return false;
		 }

		$new = imagecreatetruecolor($crop_width, $crop_height);
		$current_image = $icfunc($filename);
		imagecopyresampled($new, $current_image, 0, 0, $crop_data['x1'], $crop_data['y1'], $crop_width, $crop_height, $crop_data['w'], $crop_data['h']);
		imagejpeg($new, $new_filename, 100);
		unlink($filename);
		return  basename($new_filename);
	 }
	 
	 public function createAvatar150 ($filename)
	 {
		 $src=$this->uploaddir_full.$filename;
		 $dest=$this->uploaddir_mini. $this->random_file_name () . '.'.$this->get_file_ext(basename($filename));
		 $this->resize_image($src, $dest, $width=150, $height="auto", $rgb=0xFFFFFF, $quality=100);
		 
		 $crop_data['file']=$dest;
		 $crop_data['x1']=0;
		 $crop_data['y1']=0;
		 $crop_data['w']=150;
		 $crop_data['h']=150;
		 
		 $file_name = $this->createAvatar($crop_data, $crop_width=150, $crop_height = 150, $size="mini");
		 unlink ($dest);
		 return $file_name;
		 
	 }
	 public function createAvatar50 ($filename)
	 {
		 $src=$this->uploaddir_mini.$filename;
		 $dest=$this->uploaddir_mini. $this->random_file_name () . '.'.$this->get_file_ext(basename($filename));
		 $this->resize_image($src, $dest, $width=50, $height="auto", $rgb=0xFFFFFF, $quality=100);
		 
		 $crop_data['file']=$dest;
		 $crop_data['x1']=0;
		 $crop_data['y1']=0;
		 $crop_data['w']=50;
		 $crop_data['h']=50;
		 
		 $file_name = $this->createAvatar($crop_data, $crop_width=50, $crop_height = 50, $size="mini");
		 unlink ($dest);
		 return $file_name;
	 }
}